package com.weixiaodong.ModelDesign.适应设计模式.Iterator模式.遍历书籍程序案例演示;

/**
 * 定义书架类
 */
@SuppressWarnings("all")
public class BookShelf implements Aggregate{

    private Book[] bookShelf;

    private int maxsize;

    private int last; // 指向书架上的最后一本书

    public BookShelf(int maxsize) {
        last = -1;
        this.maxsize = maxsize;
        bookShelf = new Book[this.maxsize];
    }

    public void appendBook(Book book) {
        if (last >= this.maxsize - 1) {
            System.out.println("书架已满，无法放置新的书籍");
            return;
        }
        last++;
        bookShelf[last] = book;
    }

    public Book getBook(int index) {
        if (index >= this.maxsize) {
            throw new IndexOutOfBoundsException("索引异常");
        }
        return bookShelf[index];
    }

    public int getSize() {
        return this.last + 1;
    }

    @Override
    public Iterator iterator() {
        return new BookShelfIterator(this);
    }
}
